package com.force.abril.executive.prevision.download.transformer;

import static com.force.abril.executive.prevision.download.transformer.ExecutiveFieldMapping.FIELDS;
import static com.topi.integration.connectorapi.transformer.XmlObjectHelper.getStringField;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtilsBean2;
import org.springframework.stereotype.Component;

import br.com.abril.prevision.ExecutivePrevision;

import com.force.abril.transformer.Mapping;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.bind.XmlObject;

@Component
public class ExecutivePrevisionTransformer {

	public List<ExecutivePrevision> toPrevisionsFromSObject(
			SObject[] sfPrevisions) {
		List<ExecutivePrevision> previsions = new ArrayList<ExecutivePrevision>();
		for (SObject sfPrevision : sfPrevisions) {
			ExecutivePrevision executive = toLocalPrevision(sfPrevision);
			if (executive.getDataReserva() == null) continue;
			previsions.add(executive);
		}

		return previsions;
	}

	public ExecutivePrevision toLocalPrevision(SObject salesForceRow) {

		ExecutivePrevision prevision = new ExecutivePrevision();

		XmlObject sfPrevision = (XmlObject) salesForceRow.getField("Previsao__r");
		XmlObject sfProduct = (XmlObject) sfPrevision.getField("ProdutoAbril__r");
		XmlObject sfAdvertiser = (XmlObject) sfPrevision.getField("AnuncianteMigrado__r");
		XmlObject sfOffice = (XmlObject) sfPrevision.getField("AgenciaMigrada__r");
		
		prevision.setOffice(getStringField(sfPrevision,"AgenciaMigrada__c"));
		prevision.setAdvertiser(getStringField(sfPrevision,"AnuncianteMigrado__c"));
		prevision.setProduct(getStringField(sfPrevision,"ProdutoAbril__c"));
		prevision.defineWallet();
		
		
		prevision.setUn          ( getStringField(sfPrevision,"Un__c") );
		prevision.setProductGroup( getStringField(sfProduct,"GrupoDeProduto__c") );				
		prevision.setProductId   ( getStringField(sfProduct,"IDProduto__c") );		
		
		prevision.setAdvertiserId( getStringField(sfAdvertiser,"IDSistema__c") );
		prevision.setOfficeId( getStringField(sfOffice,"IDSistema__c") );		
		
		if (sfPrevision.getField( "DataReferenciaAjustada__c" ) != null ) {
			prevision.setDataReserva( sfPrevision.getField( "DataReferenciaAjustada__c" ).toString());
		}

		for (Mapping mapping : FIELDS) {

			try {

				BeanUtilsBean2.getInstance().setProperty(prevision,
						mapping.getKey(),
						salesForceRow.getField(mapping.getValue()));

			} catch (IllegalAccessException e) {
				e.printStackTrace();

			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}

		}

		return prevision;

	}

}
